package per.jdz.demo;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import per.jdz.demo.domain.entity.HouseData;
import per.jdz.demo.readlistener.AbstractListener;
import per.jdz.demo.utils.FileUtil;

import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * @author Jdz
 * @date 2025/2/5
 */
@SpringBootTest
@Slf4j
public class ProcessFile {

    private final String URL = "C:\\Users\\Public\\Downloads\\" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    private final String split = "\\outPart";
    private final File fileObj = new File(URL);
    private final File splitObj = new File(URL + split);
    @Test
    public void splitFile() {
        if (splitObj.exists()) {
            boolean delete = FileUtil.deleteDirectory(splitObj);
            if (!delete) {
                log.error("split文件夹删除失败");
                return;
            }
        }
        boolean mkdir = splitObj.mkdir();
        if (!mkdir) {
            log.error("文件夹创建失败");
            return;
        }
        CompletableFuture.allOf(Arrays.stream(Objects.requireNonNull(fileObj.listFiles()))
                .map(file -> CompletableFuture.runAsync(() -> {
                    log.info("开始读取文件: {}", file.getName());
                    processFile(file);
                })).toArray(CompletableFuture[]::new)).join();
    }

    private void processFile(File file) {
        if (file.isDirectory()) return;
        String fileName = file.getName();
        String prefix = fileName.substring(0, fileName.lastIndexOf("."));
        if (fileName.endsWith(ExcelTypeEnum.CSV.getValue())) {
            EasyExcel.read(file, HouseData.class, new AbstractListener<HouseData>(prefix ,ExcelTypeEnum.CSV.getValue(), splitObj.getAbsolutePath())).excelType(ExcelTypeEnum.CSV).sheet().doRead();
        } else if (fileName.endsWith(ExcelTypeEnum.XLSX.getValue())) {
            EasyExcel.read(file, HouseData.class, new AbstractListener<HouseData>(prefix, ExcelTypeEnum.XLSX.getValue(), splitObj.getAbsolutePath())).excelType(ExcelTypeEnum.XLSX).sheet().doRead();
        } else {
            log.error("文件类型不支持{}", fileName);
        }
    }

    @Test
    public void upsert() {
        for (File file : splitObj.listFiles()) {
            System.out.println(file.getName());
        }
    }

}
